﻿using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using MyMES.Domain.zmc;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Read.API.Application.Commends.Customers;
using MyMES.Read.API.Application.Commends.Enterprises;
using MyMES.Read.API.Dtos;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace MyMES.Read.API.Controllers.ZMC.Customers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
  
    public class CustomerController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly IBaseRepository<Customermanagement> customerRepository;


        public CustomerController(IMediator mediator, IBaseRepository<Customermanagement> customerRepository)
        {
            this.mediator = mediator;
            this.customerRepository = customerRepository;
        }

        /// <summary>
        /// 获取客户信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        [HttpGet]

        public Task<APIPaging<List<CustTypeDto>>> GetCustomer([FromQuery]GetCustomerCommends request, CancellationToken cancellationToken)
        {
            return mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 获取客户类型
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        [HttpGet]
        public async Task<APIResult<List<CustomerTypes>>> GetCustomertype([FromQuery]GetCustomertypeCommends request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 客户信息导出
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
  /*      [HttpGet]
        public async Task<IActionResult> ExeclCustomer()
        {
            APIResult<ArrivalnoSupplierDtos> result = new APIResult<ArrivalnoSupplierDtos>();
            result.Code = APIEnum.查询成功;
            result.Msg = "客户信息导出成功";
            var sql = "SELECT a.*,b.CustomerTypeName FROM customermanagement a LEFT JOIN customertypes b ON a.CustomerTypeId=b.CustomerTypeId  where IsDlete=false ORDER BY a.CustomerId DESC;";
            var Rlist = await customerRepository.SelectAsync(sql);

            //创建工作簿
            IWorkbook workbook = new XSSFWorkbook();

            //依据工作簿创建sheet
            ISheet sheet = workbook.CreateSheet("客户信息");
            //依据sheet创建首行
            IRow row = sheet.CreateRow(0);
            //在创建好的行中创建首行单元格
            row.CreateCell(0).SetCellValue("客户编码");
            row.CreateCell(1).SetCellValue("客户名称");
            row.CreateCell(2).SetCellValue("客户简称");
            row.CreateCell(3).SetCellValue("客户电话");
            row.CreateCell(4).SetCellValue("联系人");
            row.CreateCell(5).SetCellValue("联系人-电话");
            row.CreateCell(6).SetCellValue("是否启用");
            row.CreateCell(6).SetCellValue("客户类型");
            row.CreateCell(7).SetCellValue("删除标志位");

            //行编号
            int index = 1;
            foreach (var item in Rlist.ToList())
            {
                //sheet表中的第二行完成数据遍历
                //创建新行
                row = sheet.CreateRow(index);
           var isdele= item.IsDlete == true ? "是" : "否";
              var CustomerTypeId =  item.CustomerTypeId==1?"客户类型":"个人";
                //将所有数据依次写入到行中
                row.CreateCell(0).SetCellValue(item.CustomerNo);
                row.CreateCell(1).SetCellValue(item.CustomerName);
                row.CreateCell(2).SetCellValue(item.Customerdescris);
                row.CreateCell(3).SetCellValue(item.Customerphone);
                row.CreateCell(4).SetCellValue(item.Customeroffadd);
                row.CreateCell(5).SetCellValue(item.Customeremadd);
                row.CreateCell(6).SetCellValue(item.Isok);
                row.CreateCell(6).SetCellValue(CustomerTypeId);
                row.CreateCell(7).SetCellValue(isdele);
                //换行
                index++;
            }
          
            //excel
            byte[] buffer;
            //使用内存流出Excel的内容
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                buffer = ms.ToArray();
            }
            //导出Excel  using Microsoft.AspNetCore.StaticFiles;
            string excelMime = new FileExtensionContentTypeProvider().Mappings[".xlsx"];

           
            //导出
            return File(buffer, excelMime, "客户信息.xlsx");
        }*/



        [HttpGet]
        public async Task<IActionResult> ExeclCustomer()
        {
            try
            {
                var sql = @"SELECT a.*, b.CustomerTypeName 
                    FROM customermanagement a 
                    LEFT JOIN customertypes b ON a.CustomerTypeId = b.CustomerTypeId  
                    WHERE IsDlete = false 
                    ORDER BY a.CustomerId DESC;";

                // 确保数据完全加载到内存
                var Rlist = (await customerRepository.SelectAsync(sql)).ToList();

                // 创建Excel工作簿
                IWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet("客户信息");
         
                // 创建标题行
                IRow headerRow = sheet.CreateRow(0);
                headerRow.CreateCell(0).SetCellValue("客户编码");
                headerRow.CreateCell(1).SetCellValue("客户名称");
                headerRow.CreateCell(2).SetCellValue("客户简称");
                headerRow.CreateCell(3).SetCellValue("客户电话");
                headerRow.CreateCell(4).SetCellValue("联系人");
                headerRow.CreateCell(5).SetCellValue("联系人-电话");
                headerRow.CreateCell(6).SetCellValue("是否启用");
                headerRow.CreateCell(7).SetCellValue("客户类型");
                headerRow.CreateCell(8).SetCellValue("删除标志位");

                // 填充数据行
                int rowIndex = 1;
                foreach (var item in Rlist)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex++);

                    var CustomerTypeId = item.CustomerTypeId == 1 ? "客户类型" : "个人";
                    dataRow.CreateCell(0).SetCellValue(item.CustomerNo);
                    dataRow.CreateCell(1).SetCellValue(item.CustomerName);
                    dataRow.CreateCell(2).SetCellValue(item.Customerdescris);
                    dataRow.CreateCell(3).SetCellValue(item.Customerphone);
                    dataRow.CreateCell(4).SetCellValue(item.Customeroffadd);
                    dataRow.CreateCell(5).SetCellValue(item.Customeremadd);
                    dataRow.CreateCell(6).SetCellValue(item.Isok ? "是" : "否");
                    dataRow.CreateCell(7).SetCellValue(item.CustomerTypeId==1?"企业客户":"个人"); // 直接使用Join后的类型名称
                    dataRow.CreateCell(8).SetCellValue(item.IsDlete ? "是" : "否");
                }

                // 生成Excel文件流
                byte[] buffer;
                using (var ms = new MemoryStream())
                {
                    workbook.Write(ms);
                    buffer = ms.ToArray();
                }

                // 设置MIME类型并返回文件
                var mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                return File(buffer, mimeType, "客户信息.xlsx");
            }
            catch (Exception ex)
            {
                // 处理异常，记录日志等
                return StatusCode(500, "内部服务器错误: " + ex.Message);
            }
        }
    }
}
